// @ts-ignore
import { v4 as uuid } from 'uuid';
// @ts-ignore
import CryptoJS from 'crypto-js';

export interface OAuthSession {
  state?: string;
  codeVerifier?: string;
  codeChallenge?: string;
  redirectUrl?: string;
}

export default function useOAuthSession(refresh?: boolean): OAuthSession {
  const json = sessionStorage.getItem('OAuthSession');
  if (json && !refresh) {
    return JSON.parse(json) as OAuthSession;
  } else {
    const codeVerifier = uuid() + '-' + uuid();
    const session = {
      state: uuid(),
      codeVerifier: codeVerifier,
      codeChallenge: CryptoJS.SHA256(codeVerifier)
        .toString(CryptoJS.enc.Base64)
        .replace(/\+/g, '-')
        .replace(/\//g, '_')
        .replace(/=/g, ''),
    };
    sessionStorage.setItem('OAuthSession', JSON.stringify(session));
    return session;
  }
}
